import {topCategory} from '@/api/constants.js'
import { findAllCategory } from '@/api/category.js'
// 分类模块
export default {
  namespaced: true,
  state () {
    return {
      //分类信息集合，依赖category重新设置，保证初始化就有数据，不至于白屏
      list: topCategory.map(item => ({name: item}))
    }
  },
  // 修改分类函数,只能进行同步操作
  mutations: {
    // payload所有分类集合
    setList (state, payload) {
      state.list = payload
    },
    //显示二级分类数据
    show (state, id) {
      // const currentCategory = state.list.find(item => item.id === id)
      const currentCategory = state.list.find(item => item.id === id)
      currentCategory.open = true
    },
    //隐藏二级分类数据
    hidden (state, id) {
      const currentCategory = state.list.find(item => item.id === id)
      currentCategory.open = false
    },
  },
  // 获取分类函数，异步
  actions: {
    //获取分类数据
    async getList (context) {
      const data = await findAllCategory()
      //给每个分类加上控制二级分类显示隐藏的数据
      data.result.forEach(top => {
        top.open = false
      })
      //修改分类数据,context里有commit和state
      context.commit('setList', data.result)
    },
  }

}
